package model;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Config
{

    private static String username;
    private static String password;
    private static String hostname;
    private static String port;

    public static String getHostname()
    {
        return hostname;
    }

    public static String getPassword()
    {
        return password;
    }

    public static String getPort()
    {
        return port;
    }

    public static String getUsername()
    {
        return username;
    }

    private static String getTagValue(String sTag, Element eElement)
    {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

        Node nValue = (Node) nlList.item(0);

        return nValue.getNodeValue();
    }

    public static void readConfig()
    {
        try
        {
            File fXmlFile = new File("config.xml");

            if (fXmlFile.exists())
            {
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(fXmlFile);
                doc.getDocumentElement().normalize();

                NodeList nList = doc.getElementsByTagName("connection");

                for (int temp = 0; temp < nList.getLength(); temp++)
                {
                    Node nNode = nList.item(temp);
                    if (nNode.getNodeType() == Node.ELEMENT_NODE)
                    {
                        Element eElement = (Element) nNode;

                        hostname = getTagValue("hostname", eElement);
                        port = getTagValue("port", eElement);
                        username = getTagValue("username", eElement);
                        password = getTagValue("password", eElement);
                    }
                }
            }
        }
        catch (ParserConfigurationException | SAXException | IOException e)
        {
        }
    }
}
